import 'package:flutter/cupertino.dart'
    show
        DefaultCupertinoLocalizations,
        DatePickerDateOrder,
        CupertinoLocalizations;
import 'package:flutter/material.dart';
import 'package:furaha_mkopo/commonTool/fm_language_tool.dart';
import 'package:furaha_mkopo/page/dialog/time/fm_date_picker.dart';

class FMSelectTimePage extends StatefulWidget {
  String? time;
  Function()? onBack;
  Function(String time)? onConfirm;

  FMSelectTimePage(
      {super.key, required this.time, this.onBack, this.onConfirm});

  @override
  State<FMSelectTimePage> createState() => _FMSelectTimePageState();
}

class _FMSelectTimePageState extends State<FMSelectTimePage> {
  late DateTime curDate;
  int minYear = 1970;
  @override
  void initState() {
    super.initState();
    List<String> parts = (widget.time ?? "12-08-1983").split('-');
    if (parts.length != 3) {
      parts = ["01", "01", "1970"];
    }
    int day = int.tryParse(parts[0]) ?? 1;
    int month = int.tryParse(parts[1]) ?? 1;
    int year = int.tryParse(parts[2]) ?? 1970;
    if (year < minYear) {
      minYear = year;
    }
    curDate = DateTime(year, month, day);
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        widget.onBack?.call();
        return true;
      },
      child: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          widget.onBack?.call();
        },
        child: Scaffold(
          backgroundColor: Colors.transparent,
          body: GestureDetector(
            onTap: () {},
            child: Center(
              child: Container(
                height: 504,
                alignment: Alignment.topCenter,
                width: 311,
                margin: const EdgeInsets.symmetric(horizontal: 32),
                decoration: const BoxDecoration(
                  image: DecorationImage(
                    image:
                        AssetImage('assets/address/ic_address_dialog_bg.png'),
                  ),
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      margin: const EdgeInsets.only(top: 18, bottom: 10),
                      child: Text(
                        FMLanguageTool.getText("Please select a time"),
                        style:
                            const TextStyle(color: Color(0xFF333333), fontSize: 20),
                      ),
                    ),
                    Container(
                      margin:
                          const EdgeInsets.only(left: 12, right: 12, top: 0),
                      height: 317,
                      child: Center(
                        child: Container(
                          height: 221,
                          width: double.infinity,
                          margin: const EdgeInsets.only(left: 11, right: 11),
                          padding: const EdgeInsets.only(top: 2),
                          child: Column(
                            children: [
                              Row(
                                children: [
                                  generateTitle(FMLanguageTool.getText("Day")),
                                  generateTitle(FMLanguageTool.getText("Month")),
                                  generateTitle(
                                    FMLanguageTool.getText("Years"),
                                  ),
                                ],
                              ),
                              const SizedBox(
                                height: 3,
                              ),
                              Expanded(
                                  child: Stack(
                                children: [
                                  Center(
                                    child: Container(
                                      height: 40,
                                      width: double.infinity,
                                      margin: const EdgeInsets.only(
                                          left: 11, right: 11),
                                      decoration: const BoxDecoration(
                                        color: Color(0xFFFC7408),
                                        borderRadius: BorderRadius.all(
                                            Radius.circular(20)),
                                      ),
                                    ),
                                  ),
                                  CupertinoDatePicker(
                                    mode: CupertinoDatePickerMode.date,
                                    dateOrder: DatePickerDateOrder.dmy,
                                    minimumYear: minYear,
                                    maximumYear: DateTime.now().year,
                                    initialDateTime: curDate,
                                    onDateTimeChanged: (DateTime newDateTime) {
                                      curDate = newDateTime;
                                    },
                                  )
                                ],
                              ))
                            ],
                          ),
                        ),
                      ),
                    ),
                    GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: () {
                        widget.onConfirm?.call(
                            "${curDate.day.toString().padLeft(2, "0")}-${curDate.month.toString().padLeft(2, "0")}-${curDate.year}");
                      },
                      child: Container(
                        margin:
                            const EdgeInsets.only(top: 40, left: 20, right: 20),
                        height: 47,
                        width: double.infinity,
                        alignment: Alignment.center,
                        decoration: const BoxDecoration(
                          color: Color(0xFF000000),
                          borderRadius: BorderRadius.all(Radius.circular(8)),
                          image: DecorationImage(
                            image: AssetImage(
                                'assets/address/ic_address_arrow.png'),
                          ),
                        ),
                        child: Text(
                          FMLanguageTool.getText("Confirm"),
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 18,
                            fontWeight: FontWeight.w700,
                          ),
                        ),
                      ),
                    ),
                    GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: () {
                        widget.onBack?.call();
                      },
                      child: Container(
                        margin: const EdgeInsets.only(top: 10),
                        alignment: Alignment.center,
                        child: Text(
                          FMLanguageTool.getText("Cancel"),
                          style: const TextStyle(
                            color: Color(0xFF333333),
                            fontSize: 16,
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget generateTitle(String title) {
    return Flexible(
      flex: 1,
      child: Container(
        alignment: Alignment.center,
        child: Text(
          title,
          style: const TextStyle(
              color: Color(0xFF333333),
              fontSize: 16,
              fontWeight: FontWeight.w700),
        ),
      ),
    );
  }

  Widget generateTimeText(String text) {
    return Container(
      alignment: Alignment.center,
      margin: const EdgeInsets.only(top: 12, bottom: 12),
      child: Text(
        text,
        style: const TextStyle(
          color: Color(0xFF333333),
          fontSize: 14,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }
}

class _CustomMaterialLocalizationsDelegate
    extends LocalizationsDelegate<CupertinoLocalizations> {
  @override
  bool isSupported(Locale locale) => true;

  @override
  Future<CupertinoLocalizations> load(Locale locale) async =>
      _CustomMaterialLocalizations();

  @override
  bool shouldReload(_) => false;
}

class _CustomMaterialLocalizations extends DefaultCupertinoLocalizations {
  @override
  String datePickerMonth(int monthIndex) {
    return monthIndex.toString().padLeft(2, "0");
  }

  @override
  String datePickerDayOfMonth(int dayIndex, [int? weekDay]) {
    return dayIndex.toString().padLeft(2, "0");
  }
}
